function formatTime(time) {
	if (typeof time !== 'number' || time < 0) {
		return time
	}

	var hour = parseInt(time / 3600)
	time = time % 3600
	var minute = parseInt(time / 60)
	time = time % 60
	var second = time

	return ([hour, minute, second]).map(function(n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}).join(':')
}

function formatLocation(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude)
		latitude = parseFloat(latitude)
	}

	longitude = longitude.toFixed(2)
	latitude = latitude.toFixed(2)

	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}
var dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function(milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function(dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function(number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDay()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
	},
	parse: function(str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	}
};

var timeago = function(dateTimeStamp) { //dateTimeStamp是一个时间毫秒，注意时间戳是秒的形式，在这个毫秒的基础上除以1000，就是十位数的时间戳。13位数的都是时间毫秒。
	if (!dateTimeStamp) return
	var reg = /(\d{4})\-(\d{2})\-(\d{2})/;
	var Newdate = dateTimeStamp.replace(reg, "$1/$2/$3");
	var dateTime = new Date(Newdate).getTime()
	var minute = 1000 * 60; //把分，时，天，周，半个月，一个月用毫秒表示
	var hour = minute * 60;
	var day = hour * 24;
	var week = day * 7;
	var halfamonth = day * 15;
	var month = day * 30;
	var now = new Date().getTime(); //获取当前时间毫秒
	var diffValue = now - dateTime; //时间差
	var result;
	if (diffValue < 0) {
		return;
	}
	var minC = diffValue / minute; //计算时间差的分，时，天，周，月
	var hourC = diffValue / hour;
	var dayC = diffValue / day;
	var weekC = diffValue / week;
	var monthC = diffValue / month;
	if (monthC >= 1 && monthC <= 3) {
		result = " " + parseInt(monthC) + "月前"
	} else if (weekC >= 1 && weekC <= 3) {
		result = " " + parseInt(weekC) + "周前"
	} else if (dayC >= 1 && dayC <= 6) {
		result = " " + parseInt(dayC) + "天前"
	} else if (hourC >= 1 && hourC <= 23) {
		result = " " + parseInt(hourC) + "小时前"
	} else if (minC >= 1 && minC <= 59) {
		result = " " + parseInt(minC) + "分钟前"
	} else if (diffValue >= 0 && diffValue <= minute) {
		result = "刚刚"
	} else {
		var datetime = new Date();
		datetime.setTime(dateTime);
		var Nyear = datetime.getFullYear();
		var Nmonth = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
		var Ndate = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
		var Nhour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
		var Nminute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
		var Nsecond = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
		result = Nyear + "-" + Nmonth + "-" + Ndate
	}
	return result;
}


function tost(text, isState = false) {
	uni.showToast({
		title: text,
		icon: isState ? "success" : "none"
	})
}

function verifyPhone(phone) { // 判断电话号码
	const myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
	if (phone.length < 11) {
		tost("手机号码最短需要 11 个位")
		return false
	} else {
		if (!myreg.test(phone)) {
			tost("手机号格式有误")
			return false
		}
	}
	return true
}

function checkPassword(str) { // 过滤密码
	var reg1 = /[!@#$%^&*()_?<>{}]{1}/;
	var reg2 = /([a-zA-Z0-9!@#$%^&*()_?<>{}]){6,16}/;
	var reg3 = /[a-zA-Z]+/;
	var reg4 = /[0-9]+/;
	if (reg2.test(str) && reg3.test(str) && reg4.test(str)) {
		return true;
	} else if (!reg2.test(str)) {
		tost("密码长度在6-16位");
		return false;
	} else if (!reg3.test(str)) {
		tost("密码需含有字母");
		return false;
	} else if (!reg4.test(str)) {
		tost("密码需含有数字");
		return false;
	}
}

function setStorage(key, data) { // 设置缓存
	uni.setStorageSync(key,data)
}

function getStorage(key) { //获取缓存
	const data = uni.getStorageSync(key) || null;
	return data
}

function rad(d) {
	return d * Math.PI / 180.0;
}

/** 
 * 谷歌地图计算两个坐标点的距离 
 * @param lng1  经度1 
 * @param lat1  纬度1 
 * @param lng2  经度2 
 * @param lat2  纬度2 
 * @return 距离（千米） 
 */
function getDistance(lng1, lat1, lng2, lat2) {
	var EARTH_RADIUS = 6378.137; //地球半径  
	var radLat1 = rad(lat1);
	var radLat2 = rad(lat2);
	var a = radLat1 - radLat2;
	var b = rad(lng1) - rad(lng2);
	var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
		Math.cos(radLat1) * Math.cos(radLat2) *
		Math.pow(Math.sin(b / 2), 2)));
	s = s * EARTH_RADIUS;
	s = Math.round(s * 10000) / 10000;
	s = toFixed(s)
	return s;
}

function toFixed(value) {
	var number = Number(value.toString().match(/^\d+(?:\.\d{0,2})?/));
	return number > 1 ? number + 'km' : number * 1000 + 'm'
}


function getNowDate() {
	var date = new Date();
	var sign1 = "-";
	var sign2 = ":";
	var year = date.getFullYear() // 年
	var month = date.getMonth() + 1; // 月
	var day = date.getDate(); // 日
	var hour = date.getHours(); // 时
	var minutes = date.getMinutes(); // 分
	var seconds = date.getSeconds() //秒
	var weekArr = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天'];
	var week = weekArr[date.getDay()];
	// 给一位数数据前面加 “0”
	if(month >= 1 && month <= 9) {
		month = "0" + month;
	}
	if(day >= 0 && day <= 9) {
		day = "0" + day;
	}
	if(hour >= 0 && hour <= 9) {
		hour = "0" + hour;
	}
	if(minutes >= 0 && minutes <= 9) {
		minutes = "0" + minutes;
	}
	if(seconds >= 0 && seconds <= 9) {
		seconds = "0" + seconds;
	}
	var currentdate = {
		year: String(year),
		month: String(month),
		day: String(day),
		week: String(week)
	}
	return currentdate;
}


function getSystemInfo () {
 	 let data = uni.getSystemInfoSync()
	 return data
}

let chooseImage = (count=6,sourceType)=>{
	return new Promise((resolve,reject)=>{
		uni.chooseImage({
			count:count,
			sizeType: ['original', 'compressed'],
			sourceType: sourceType,
			success: (res) => {
				resolve(res)
			},
			fail: (err) => {
				reject(err)
			}
		})
	})
}

let ages = (str) => { // 计算年龄
	var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
	if(r == null) return false;
	var d = new Date(r[1], r[3] - 1, r[4]);
	if(d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3] && d.getDate() == r[4]) {
		var Y = new Date().getFullYear();
		return(Y - r[1]);
	}
	return("输入的日期格式错误！");
}


module.exports = {
	formatTime,
	formatLocation,
	dateUtils,
	tost,
	verifyPhone,
	setStorage,
	getStorage,
	checkPassword,
	timeago,
	getDistance,
	getNowDate,
	getSystemInfo,
	chooseImage,
	ages
}
